package com.mac.intellect_flow.admin.controller.system;

import com.mac.intellect_flow.framework.dto.SysUserDto;
import com.mac.intellect_flow.framework.util.SecurityUtils;
import com.mac.intellect_flow.reply.PageParam;
import com.mac.intellect_flow.reply.PageResult;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.sys.entity.SysDept;
import com.mac.intellect_flow.sys.entity.SysRole;
import com.mac.intellect_flow.sys.entity.SysUser;
import com.mac.intellect_flow.sys.service.SysDeptService;
import com.mac.intellect_flow.sys.service.SysPostService;
import com.mac.intellect_flow.sys.service.SysRoleService;
import com.mac.intellect_flow.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户管理
 * 
 * @author mac
 */
@Tag(name = "用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysPostService postService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 获取用户列表
     */
    @Operation(summary = "获取用户列表")
    //@PreAuthorize("@ps.hasPermi('system:user:list')")
    @GetMapping("/list")
    public R<PageResult<SysUser>> list(SysUser user, PageParam pageParam) {
        return R.success(userService.queryPage(user,pageParam));
    }

/*    @PreAuthorize("@ps.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }*/


 /*   @PreAuthorize("@ps.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return R.success(message);
    }*/

 /*   @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }*/

    /**
     * 根据用户编号获取详细信息
     */
    @Operation(summary = "根据用户编号获取详细信息")
    @PreAuthorize("@ps.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public R getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Map<String, Object> data = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        data.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        data.put("posts", postService.selectPostAll());
        if (Objects.nonNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            data.put("data", sysUser);
            data.put("postIds", postService.selectPostListByUserId(userId));
            data.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return R.success(data);
    }

    /**
     * 新增用户
     */
    @Operation(summary = "新增用户")
    @PreAuthorize("@ps.hasPermi('system:user:add')")
    @PostMapping
    public R add(@Validated @RequestBody SysUser user) {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return R.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return R.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.error("新增用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        SysUserDto userDto = new SysUserDto();
        BeanUtils.copyProperties(user, userDto);
        return R.success(userService.insertUser(userDto));
    }

    /**
     * 修改用户
     */
    @Operation(summary = "修改用户")
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @PutMapping
    public R edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return R.error("修改用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return R.error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        SysUserDto userDto = new SysUserDto();
        BeanUtils.copyProperties(user, userDto);
        return R.success(userService.updateUser(userDto));
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户")
    @PreAuthorize("@ps.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return R.error("当前用户不能删除");
        }
        return R.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Operation(summary = "重置密码")
    @PreAuthorize("@ps.hasPermi('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return R.success(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @Operation(summary = "状态修改")
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        return R.success(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @Operation(summary = "根据用户编号获取授权角色")
    @PreAuthorize("@ps.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public R authRole(@PathVariable("userId") Long userId) {
        Map<String, Object> data = new HashMap<>() ;
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        data.put("user", user);
        data.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return R.success(data);
    }

    /**
     * 用户授权角色
     */
    @Operation(summary = "用户授权角色")
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @PutMapping("/authRole")
    public R insertAuthRole(Long userId, Long[] roleIds) {
        if (Objects.isNull(userId)){
            return R.error("用户ID不能为空");
        }
        if (ArrayUtils.isEmpty(roleIds)) {
            return R.error("角色ID不能为空");
        }
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return R.success();
    }

}
